﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using BuyTicket.Models;
using BuyTicket.Views;
using System.Web;

namespace BuyTicket.Service
{
    class BuyTicketServiceV2
    {
        static HttpResponse m_Response = null;
        static X509CertificateCollection m_X509 = null;
        static string m_Cookies = null;

        static BuyTicketServiceV2()
        {
            m_X509 = new X509CertificateCollection(){
                new X509Certificate(Properties.Resources.x509)
            };
        }

        public static string Cookies
        {
            get { return m_Cookies; }
        }

        public static void Navigate(string url)
        {
            WebBrowserWindow window = new WebBrowserWindow();
            window.Navigate(m_Cookies, url);
            window.ShowDialog();
        }

        public static Stream GetVerifyImage()
        {
            IPEndPoint endpoint = GetHost();
            HttpHeader header = new HttpHeader()
            {
                Url = "/otsweb/main.jsp",
                Host = "dynamic.12306.cn",
                Accept = "text/heml, */*",
            };
            bool isRequest = false;
            m_Response = HttpHelperV2.Get(endpoint, header, m_X509);
            if (m_Response != null)
            {
                if (m_Response.Header.StartsWith("HTTP/1.1 200"))
                {
                    //先校正保存cookies
                    AdjustCookies();
                    header.Url = "/otsweb/loginAction.do?method=init";
                    header.Cookies = m_Cookies;
                    header.Referer = "https://dynamic.12306.cn/otsweb/main.jsp";
                    m_Response = HttpHelperV2.Get(endpoint, header, m_X509);
                    if (m_Response != null)
                    {
                        if (m_Response.Header.StartsWith("HTTP/1.1 200"))
                        {
                            isRequest = true;
                        }
                    }
                }
            }
            if (isRequest)
            {
                header.Url = "/otsweb/passCodeAction.do?rand=sjrand";
                header.Accept = "image/*, */*";
                header.Referer = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init";
                m_Response = HttpHelperV2.Get(endpoint, header, m_X509);
                if (m_Response != null)
                {
                    if (m_Response.Header.StartsWith("HTTP/1.1 200"))
                    {
                        return new MemoryStream(m_Response.Body);
                    }
                }
            }
            return null;
        }

        static void AdjustCookies()
        {
            m_Cookies = HttpHelperV2.GetCookies(m_Response.Header);
        }

        class LoginAsynSuggest
        {
            public string LoginRand { get; set; }
            public string RandError { get; set; }
        }

        public static bool Login(string name, string pass, string verifyCode, out string error)
        {
            IPEndPoint endpoint = GetHost();
            //先请求loginRand值
            HttpHeader header = new HttpHeader()
            {
                Url = "/otsweb/loginAction.do?method=loginAysnSuggest",
                Host = "dynamic.12306.cn",
                Accept = "application/json,  */*",
                Referer = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init",
                Cookies = m_Cookies
            };
            string loginRand = null;
            m_Response = HttpHelperV2.Post(endpoint, header, m_X509);
            if (m_Response != null)
            {
                if (m_Response.Header.StartsWith("HTTP/1.1 200") && m_Response.Body != null)
                {
                    //{"loginRand":"359","randError":"Y"}
                    LoginAsynSuggest loginAsynSuggest = JsonConvert.DeserializeObject<LoginAsynSuggest>(Encoding.UTF8.GetString(m_Response.Body));
                    loginRand = loginAsynSuggest.LoginRand;
                }
                else
                {
                    error = "访问失败";
                }
            }
            else
            {
                error = "访问失败，主机没有回应";
                return false;
            }
            if (!string.IsNullOrEmpty(loginRand))
            {
                header.Url = "/otsweb/loginAction.do?method=login";
                header.Accept = "text/html, */*";
                header.Body = string.Format("loginRand={0}&refundLogin=N&refundFlag=Y&loginUser.user_name={1}&nameErrorFocus=&user.password={2}&passwordErrorFocus=&randCode={3}&randErrorFocus=",
                    loginRand,
                    name,
                    pass,
                    verifyCode);
                m_Response = HttpHelperV2.Post(endpoint, header, m_X509);
            }
            else
            {
                error = "获取LoginRand参数失败";
                return false;
            }
            //继续登录
            if (m_Response != null)
            {
                if (m_Response.Header.StartsWith("HTTP/1.1 200") && m_Response.Body != null)
                {
                    string strHtml = Encoding.UTF8.GetString(m_Response.Body);
                    if (strHtml.Contains("欢迎您登录中国铁路客户服务中心网站"))
                    {
                        error = "";
                        return true;
                    }
                    else if (strHtml.Contains("当前访问用户过多，请稍后重试!"))
                    {
                        error = "当前访问用户过多，请稍后重试!";
                    }
                    else if (strHtml.Contains("请输入正确的验证码！</span>"))
                    {
                        error = "请输入正确的验证码!";
                    }
                    else
                    {
                        error = "各种登录失败，兄弟，理解万岁吧！";
                    }
                }
                else
                {
                    error = "HTTP响应错误:" + Utility.SplitString(m_Response.Header,
                        "HTTP/1.1 ",
                        " ");
                }
            }
            else
            {
                error = "超时，主机没有反映！";
            }
            return false;
        }

        public static bool GetTickets(out string strHtml)
        {
            IPEndPoint endpoint = GetHost();
            HttpHeader header = new HttpHeader()
            {
                Url = string.Format("/otsweb/order/querySingleAction.do?{0}",
                    Global.MyTicketArgs.ToString()),
                Host = "dynamic.12306.cn",
                Accept = "text/plain, */*",
                Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init",
                Cookies = m_Cookies,
            };
            m_Response = HttpHelperV2.Get(endpoint, header, m_X509);
            if (m_Response != null)
            {
                if (m_Response.Header.StartsWith("HTTP/1.1 200"))
                {
                    if (m_Response.Body != null)
                    {
                        strHtml = Encoding.UTF8.GetString(m_Response.Body);
                        return true;
                    }
                }
            }
            strHtml = "";
            return false;
        }

        public static bool Order(Ticket ticket, out string strHtml)
        {
            strHtml = string.Empty;
            IPEndPoint endpoint = GetHost();
            RequestArgs request = new RequestArgs()
            {
                Url = "/otsweb/order/querySingleAction.do?method=submutOrderRequest",
                Host = "dynamic.12306.cn",
                Accept = "text/*",
                Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init",
                Cookie = m_Cookies,
                Body = ticket.ToString()
            };
            m_Response = HttpHelper.Post(endpoint, request, m_X509);
            if (m_Response != null)
            {
                string location = HttpHelper.ParseLocation(m_Response.Header);
                if (m_Response.Header.StartsWith("HTTP/1.1 302")
                    && location.Contains("confirmPassengerAction.do"))
                {
                    //转向确认购票页面
                    request.Url = location;
                    m_Response = HttpHelper.Get(endpoint, request, m_X509);
                    if (m_Response != null)
                    {
                        if (m_Response.Header.StartsWith("HTTP/1.1 200")
                            && m_Response.Body != null)
                        {
                            strHtml = Encoding.UTF8.GetString(m_Response.Body);
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        static IPEndPoint m_EndPoint = null;
        static IPEndPoint GetHost()
        {
            if (m_EndPoint != null)
                return m_EndPoint;
            try
            {
                var address = Dns.GetHostAddresses("dynamic.12306.cn");
                if (address.Length > 0)
                {
                    m_EndPoint = new IPEndPoint(address[0], 443);
                    return m_EndPoint;
                }
            }
            catch (Exception)
            {
            }
            return new IPEndPoint(IPAddress.Parse("122.228.243.22"), 443);
        }
    }
}